package com.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.constant.Constant;
import com.demo.entity.Action;
import com.demo.entity.Message;
import com.demo.entity.Role;
import com.demo.entity.User;
import com.demo.entity.Vo.RoleVo;
import com.demo.enums.MessageRankEnum;
import com.demo.mapper.ActionMapper;
import com.demo.mapper.RoleMapper;
import com.demo.mapper.UserMapper;
import com.demo.response.Result;
import com.demo.service.IRoleService;
import com.demo.service.IUserService;
import com.demo.websocket.WebSocketServer;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色信息表 服务实现类
 * @author ZM
 * @since 2020-11-19
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Resource
    RoleMapper roleMapper;
    @Autowired
    IUserService userService;
    @Resource
    ActionMapper actionMapper;
    @Resource
    UserMapper userMapper;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 新增角色
     * @param role   实体对象
     * @return
     */
    @Override
    public Result addRole(Role role) throws Exception {
        log.info(String.valueOf(role.getRoleName().length()));
        Integer id = roleMapper.getRoleIdByName(role.getRoleName());
        if (id == null){
            boolean flag = this.save(role);
        }else {
            throw new Exception("该角色名称已存在");
        }
        return Result.success();
    }

    /**
     * 编辑角色
     * @param role   实体对象
     * @return
     */
    @Override
    public Result updateRole(Role role) {
        if (role.getRoleId() == null ||role.getUpdatedUserId() == null){
            return Result.error(Constant.KEY_ID);
        }
        role.setUpdatedTime(new Date());
        boolean flag = this.updateById(role);
        if (flag == false) {
            return Result.error(Constant.DB_ERROR);
        }

        List<User> users = userMapper.queryUserByRole(role.getRoleId());
        if (users != null && users.size() > 0) {
            //发送消息
            try {
                Message message = new Message();
                message.setMessageRank(MessageRankEnum.OFF_LINE.getValue());
                webSocketServer.sendToUser2(message, users.stream().map(item -> String.valueOf(item.getUserId())).collect(Collectors.toList()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success();
    }

    /**
     * 删除角色
     * @param deleteUserId  删除人ID
     * @param roleId   角色ID
     * @return
     */
    @Override
    public Result deleteRole(Integer roleId,Integer deleteUserId) throws Exception {
        //查询此角色是否有用户使用
        User user = userMapper.getUserByRoleId(roleId);
        if (user != null){ throw new Exception("该角色已有用户使用,不能删除"); }
        if (roleId.equals(11) || roleId.equals(12) || roleId.equals(13) || roleId.equals(14)){
            throw new Exception("系统角色，无权删除");
        }

        Role role = new Role();
        role.setRoleId(roleId);
        role.setDeletedUserId(deleteUserId);
        role.setDeletedTime(new Date());
        boolean flag = this.updateById(role);
        if (flag == false) {
            return Result.error(Constant.DB_ERROR);
        }
        return Result.success();
    }

    /**
     * 角色列表
     * @param pageNumber     页码
     * @param pageSize       每页数量
     * @param roleId         角色ID
     * @return
     */
    @Override
    public Result roleList(Integer pageNumber, Integer pageSize, Integer roleId) {
        IPage<Role> page = new Page<>(pageNumber,pageSize);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(roleId != null,"role_id",roleId);
        queryWrapper.isNull("deleted_user_id");
        queryWrapper.orderByDesc("role_id");
        page = roleMapper.selectPage(page,queryWrapper);
        List<Role> list = new ArrayList<>(page.getRecords());

        List<RoleVo> roleVoList = new ArrayList<>();
        for (Role role : list){
            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(role,roleVo);
//            roleVo.setCreateName(userService.getUnameById(role.getCreatedUserId()));
//            roleVo.setUpdateName(userService.getUnameById(role.getUpdatedUserId()));
            String action = role.getRoleActions();
            List<Integer> actionList = new ArrayList<>();
            if (!StrUtil.isEmpty(action)){
                String[] strings = action.split(",");
                for (String s: strings){
                    actionList.add(Integer.parseInt(s));
                }
                QueryWrapper<Action> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.in("action_id",actionList);
                roleVo.setRoleActionsName(actionMapper.selectList(queryWrapper1));
            }
            roleVoList.add(roleVo);
        }
        PageInfo<RoleVo> pageInfo = new PageInfo<>(roleVoList);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setPages((int) page.getPages());
        if (pageNumber.equals(page.getPages())){
            pageInfo.setIsLastPage(false);
        }else {pageInfo.setIsLastPage(true);}
        return Result.success(pageInfo);
    }

    /**
     * 通过角色ID，获取名称
     * @param roleId   角色ID
     * @return
     */
    @Override
    public String getRoleNameById(Integer roleId) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        queryWrapper.select("role_name");
        Role role = roleMapper.selectOne(queryWrapper);
        if (role!= null){
            return role.getRoleName();
        }
        return null;
    }

    /**
     * 获取角色
     * @param roleId   角色Id
     * @return
     */
    @Override
    public Role getRoleAll(Integer roleId) {
        return this.getById(roleId);
    }


}
